package com.jade.bss.customer.menu.impl;

import java.util.List;
import javax.inject.Named;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;

import com.jade.bss.customer.menu.Menu;
import com.jade.bss.customer.menu.MenuDao;
import com.jade.bss.base.BssException;
import com.jade.framework.base.criterion.Criteria;
import com.jade.framework.base.criterion.sql.SqlUtils;
import com.jade.framework.base.util.PagingList;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.cache.annotation.Caching;

/**
 * 采用JPA方式实现的菜单数据访问接口。
 */
@Named ("bss_menuDao")
public class JpaMenuDao implements MenuDao
{
    protected static final String SQL = "SELECT menu FROM Menu menu";
    @PersistenceContext (unitName = "default")
    protected EntityManager entityManager;

    @Caching (evict = {@CacheEvict (value = "bss.menu.g", key = "#menu.id"),
            @CacheEvict (value = "bss.menu.l", allEntries = true),
            @CacheEvict (value = "bss.menu.q", allEntries = true)})
    public void add(Menu menu)
            throws BssException
    {
        entityManager.persist(menu);
    }

    @Caching (evict = {@CacheEvict (value = "bss.menu.g", key = "#menu.id"),
            @CacheEvict (value = "bss.menu.l", allEntries = true),
            @CacheEvict (value = "bss.menu.q", allEntries = true)})
    public void update(Menu menu)
            throws BssException
    {
        entityManager.merge(menu);
    }

    @Caching (evict = {@CacheEvict (value = "bss.menu.g", key = "#menu.id"),
            @CacheEvict (value = "bss.menu.l", allEntries = true),
            @CacheEvict (value = "bss.menu.q", allEntries = true)})
    public void remove(Menu menu)
            throws BssException
    {
        Menu old = entityManager.find(Menu.class, menu.getId());
        if (old != null) {
            entityManager.remove(old);
        }
    }

    @Cacheable (value = "bss.menu.g", key = "#id")
    public Menu get(long id)
    {
        return entityManager.find(Menu.class, id);
    }

    @Cacheable (value = "bss.menu.l", key = "#criteria")
    public List<Menu> list(Criteria criteria)
    {
        return SqlUtils.sqlQueryWithoutCount(SQL, entityManager, criteria);
    }

    @Cacheable (value = "bss.menu.q", key = "#criteria")
    public PagingList<Menu> query(Criteria criteria)
    {
        return SqlUtils.sqlQuery(SQL, entityManager, criteria);
    }

}
